<?php
namespace Sdk\Opene;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;

class callOpeneApiUtil
{
    private const URL = "https://fbo.opene.com";

    private const USER_NAME = "ECHAMP";
    private const USER_PASSWORD = "De2zch,kzeGWO#NS";

    public static function callOpeneApi($action, $method, $data)
    {
        try {
            $client = new Client();
            $url = self::URL . $action;
            $headers = [
                'Authorization' => "Basic ".base64_encode(self::USER_NAME.":".self::USER_PASSWORD),
                'Content-Type' => 'application/json',
                'chraset' => 'UTF-8'
            ];
            if ('post' == strtolower($method)) {
                $response = $client->request($method, $url, ['headers' => $headers, 'json' => $data]);
            } else {
                $arr = [];
                if (!empty($data)) {
                    foreach ($data as $k => $v) {
                        $arr[] = "$k=$v";
                    }
                    $url .= "?".implode("&", $arr);
                }
                $response = $client->request($method, $url, ['headers' => $headers]);
            }
            $status = $response->getStatusCode();
            if (200 == $status) {
                $result = $response->getBody()->getContents();
                return json_decode($result, true);
            } else {
                return [];
            }
        } catch (ClientException $e) {
            return [];
        }
    }

}